// subpages1/promotion/promotion.js
var app = getApp();
Page({
  data: {
    pageData:{          //页面参数，
      gid:'',
      shareType: 'default',
      shareBillImage: ''
    },
    detail:{
      content:'',   //推广文案
      picture:[]    //图片列表
    },
    selectedImages:[],
    isAuth:false,
  },
  onLoad: function (options) {
    let that  = this;
    this.setData({
      pageData:options
    })
    wx.showLoading({
      title:"加载中..."
    })
    this.getShareImage((firstPath)=>{ //取得第一张海报图
      wx.request({
        url: app.globalData.requestUrl,
        data: {
          map:"applet_goods_spread",
          gid:options.gid
        },
        success: function(res) {
          if (res.data.ec !=200) {
            wx.showToast({
              title: res.data.em,
              icon:'none',
              duration: 2000
            });
            return;
          }
          res.data.picture.unshift(firstPath);  //添加一张海报图
          res.data.picture=res.data.picture.filter(v=>!!v);   //过滤无效数据
          that.setData({
            detail: res.data
          })
        },
        complete: function() {
          wx.hideLoading();
        }
      });
    })
    // 先获取授权
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            fail(){
              wx.showModal({
                title:"检测到保存图片到相册的权限未开启，是否前往开启？",
                confirmText:"前往",
                success(res){
                  if(res.confirm){
                    wx.openSetting();
                  }
                  if(res.cancel){
                    wx.navigateBack();
                  }
                }
              })
            },
            success () {
              console.log("写相册授权成功");
            }
          })
        }
      }
    })
  },
  onShow: function () {

  },
  checkboxChange(e){
    let checkedArr = e.detail.value;
    console.log(checkedArr);
    try{
      this.data.selectedImages = checkedArr.map(i=>this.data.detail.picture[i]);
    }catch(e){
      console.error(e);
    }
  },
  copy(){
    if(!this.data.detail.content){
      wx.showToast({
        title: '没有内容可复制...',
        icon:"none"
      })
      return;
    }
    wx.setClipboardData({
      data: this.data.detail.content,
      success (res) {
        wx.showToast({
          title: '复制成功',
        })
      }
    })
  },
  getShareImage(resolve){
    var that = this;
    var id = that.data.pageData.gid;
    var goodsType = that.data.pageData.shareType;
    var shareBillImage = that.data.pageData.shareBillImage;
    var data = {
      map: goodsType == 'ider' ? 'applet_goods_share_poster_v2' : 'applet_goods_share_poster',
      id: id
    }
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function(res) {
        if (res.data.ec == 200) {
          var detailInfo = res.data.data;
          if (goodsType == 'ider') { // 用户分享图
            var memberSahreImg = detailInfo.memberShareImg;
            wx.getImageInfo({
              src: memberSahreImg,
              success: function (r) {
                let merchantPage = r.path;
                // 开始画图
                that.creatIderShareImg(resolve, merchantPage);
              }
            })
          } else {
            var curimg = detailInfo.shareImg;
            resolve(curimg);   //回传图片地址
          }
        } else {
          wx.showToast({
            title: res.data.em,
            icon:"none"
          })
        }
      }
    });
  },
  // Ider分享图
  creatIderShareImg: function (resolve, merchantShareImg) {
    var that = this;
    var shareType = that.data.pageData.shareType;
    var cover = that.data.pageData.shareBillImage;

    var res = wx.getSystemInfoSync();
    let winW = res.windowWidth;
    let winH = res.windowHeight
    
    that.setData({
      canvasW: winH,
      canvasH: winH
    });

    if (shareType == 'ider') {
      // 自定义分享海报
      wx.getImageInfo({
        src: cover,
        success: function (res) {
          var shareCanvas = wx.createCanvasContext('share-cover');
          shareCanvas.drawImage(res.path, 0, 0, winW, winH);
          
          let qrWidth = winW / 10;
          let msH = winH - (winH / 10) - (qrWidth / 2) - 10;
          shareCanvas.drawImage(merchantShareImg, qrWidth / 2, msH, qrWidth * 2, qrWidth * 2);

          shareCanvas.draw(false, function (e) {
            wx.canvasToTempFilePath({
              x: 0,
              y: 0,
              width: winW,
              height: winH,
              canvasId: 'share-cover',
              fileType: 'jpg',
              quality: 1,
              success: function (res) {
                var tempFilePathShow = res.tempFilePath;
                resolve(tempFilePathShow);
              },
              fail: function () {
                wx.hideLoading();
              }
            })
          });
        }
      });
      return false;
    } else {
      // 默认分享海报
    }
    return false;
  },
  save(){
    let len = this.data.selectedImages.length;
    let i=0;
    if(len<1) {
      wx.showToast({
        title: '请先选择图片',
        icon:"none"
      })
      return;
    }
    wx.showLoading({
      title:"保存中..."
    })
    this.data.selectedImages.forEach(v=>{
      wx.getImageInfo({
        src:v,
        success(res){
          const {path} =res;
          console.log(path);
          wx.saveImageToPhotosAlbum({
            filePath:path,
            success(){
              i++;
              if(i>=len){
                wx.hideLoading();
                setTimeout(wx.showToast,0,{
                  title: '保存成功'
                })
              }
            }
          })
        },
        fail(){
          console.log(`下载图片${v}失败`);
          wx.hideLoading();
          setTimeout(wx.showToast,0,{
            title: '下载图片出错',
            icon:"none"
          })
        }
      })
    })
  }
})